<template>
    <div>
        <h3>发表评论</h3>
        <hr>
        <textarea placeholder="输入评论内容，最多120个字" maxlength="120" v-model="comment"></textarea>
        <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
        <div class="comment-list" v-for="(item, index) in comments" :key="index">
            <div class="comment-item">
                <div class="comment-item-title">第{{index}}楼{{item.user_name}}&nbsp;用户:&nbsp;发表时间:{{item.add_time |
                    dateFormat}}
                </div>
                <div class="comment-item-body">{{item.content}}</div>
            </div>
        </div>
        <mt-button type="danger" size="large" plain @click="loadMore">加载更多</mt-button>

    </div>
</template>

<script lang="ts">
  import {Component, Prop, Vue} from 'vue-property-decorator';
  import {Toast} from 'mint-ui';


  @Component
  export default class Comment extends Vue {
    @Prop() private id!: number;
    private pageindex: number = 1;
    private comments: any[] = []; // 已经发表的评论
    private comment: string = '';

    private created(): void {
      this.getComment();
    }

    private async getComment() {
      const {data} = await this.$http.get('http://www.liulongbin.top:3005/api/getcomments/' +
        this.id + '?pageindex=' + this.pageindex);
      if (data.status === 0) {
        this.comments = this.comments.concat(data.message);
      }
    }

    /**
     * 加载更多评论内容
     */
    private loadMore(): void {
      this.pageindex++;
      this.getComment();
    }

    private async postComment() {
      if (this.comment.trim().length === 0) {
        return Toast('请填写评论内容！');
      }
      const {response} = await this.$http.post('http://www.liulongbin.top:3005/api/postcomment/' + this.id,
        {
          content: this.comment,
        });
      if (response.status === 0) {
        this.comments.unshift({
          user_name: '匿名用户',
          add_time: new Date(),
          content: this.comment.trim(),
        });
        this.comment = '';
      }
      console.log(response);
    }
  }
</script>

<style scoped lang="scss">
    textarea {
        font-size: 14px;
        margin: 0;
    }

    .comment-list {
        margin-top: 4px;

        .comment-item {
            line-height: 30px;

            .comment-item-title {
                font-size: 14px;
                background-color: #dddddd;
            }

            .comment-item-body {
                font-size: 14px;
                text-indent: 2em;
            }
        }
    }
</style>
